package com.thread;

/**
 * Created by john on 2016/4/7.
 */
public class ThreadTest3 extends Thread{

    private int count = 3000;
    /**
     * 结果：
     * 2662---
     线程停止
     run end
     */
   /* @Override
    public void run() {

            for(int i =0;i<count;i++){
                if(this.isInterrupted()){
                    System.out.println("线程停止");
                }else{
                    count --;
                    System.out.println(count+"---");
                }
            }
        //虽然this.isInterrupted()为true ，跳出了for循环，但是for循环之后的程序还会继续执行。--所以通过break跳出线程执行不太靠谱
        System.out.println("run end");
    }*/

    /**
     * 结果：
     * 2662---
     线程停止
     Exception in thread "Thread-0" java.lang.IllegalThreadStateException
     at com.thread.ThreadTest3.run(ThreadTest3.java:17)
     */
    @Override
    public void run() {
        try {
            for(int i =0;i<count;i++){
                if(this.isInterrupted()){
                    System.out.println("线程停止");
                    throw new InterruptedException();
                }else{
                    count --;
                    System.out.println(count+"---");
                }
            }
            //前面抛出异常，终止程序执行
            System.out.println("run end");
        } catch (InterruptedException e) {
            System.out.println("catch 异常");
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Thread t =   new ThreadTest3();
        t.start();
        Thread.sleep(10);
        t.interrupt();
    }
}
